<?php
/*
Plugin Name: Расписание курсов
Plugin URI: http://URI_страницы_с_описанием_плагина
Description: Расписание курсов занятий.
Version: 0.6.2.5
Author: yarrrman
Author URI: http://URI_страницы_автора_плагина
License: тип лицензии плагина, например, GPL2
*/

global $DEBUG_MODE;
$DEBUG_MODE= true;


function get_current_user_role() {
	global $wp_roles;
	$current_user = wp_get_current_user();
	$roles = $current_user->roles;
	$role = array_shift($roles);
	return $wp_roles->role_names[$role];
}
function get_user_role($user) {
	global $wp_roles;
	$roles = $user->roles;
	$role = array_shift($roles);
	return $wp_roles->role_names[$role];
}
function my_plugin($atts, $content=nul){
	global $wpdb;
  	include_once "includes/functions.php";
  	include_once "includes/header.php";
  	include_once "includes/user_view.php";
  	include_once "includes/client_view.php";
  	include_once "includes/profiles.php";
  	include_once "includes/mails.php";
  	

  	$user = UsersORM::getUser();

  	/*
  	//DEBUG  payment
  	echo '<form action="/blog/wp-content/plugins/timetable/includes/payreq.php" method="POST">
		<input type="text" placeholder="amount" name="amount" value="100" ><br>
		<input type="text" placeholder="userid" name="userid" value="000000016_20140726115526_g70EwHr1wOfMe7HnBjZpocjh5W39lF1kf8mjbeS" ><br>
		<input type="text" placeholder="paymentid" name="paymentid" value="14758" ><br>
		<input type="text" placeholder="key" name="key" value="" ><br>
		<input type="text" placeholder="paymode" name="paymode" value="1" ><br>
		<input type="text" placeholder="userid_extra" name="userid_extra" value="" ><br>
		<input type="text" placeholder="orderid" name="orderid" value="" ><br>
		<input type="text" placeholder="test" name="test" value="" ><br>
		<input type="submit">
	</form>';
	*/

	
	DebugOut($user,1,1);


	if(isset($user["id"])){
		$send_mails = getSendedTimeMails($user);
		$inbox_mails = getInboxTimeMails($user);

		
		getMailBar($send_mails, $inbox_mails);		
	}

	if(strpos($content, "main") > -1){
		$view = new ViewORM('clientcourse');
		if($view->granted){
		 		createView($view);
		 	}
  	}

  	if(strpos($content, "twig") > -1){


  		createTwigView();

		/*$view = new ViewORM('clientcourse');
		if($view->granted){
		 		createView($view);
		 	}
		*/
  	}

	/*
	if(strpos($content, "profiles") > -1){
		$view = new ClientORM();
  		createClientView($view);
	}
	*/

	if(strpos($content, "profiles") > -1){
		
		DebugOut($user,1,1);
		DebugOut($user['role_status'] ,0,0);
		DebugOut($user,1,0);

		UserProfile($user['role_status']);

	}

  	if( strpos($content, "admin") > -1 && $user['role_status'] <= 2 && $user['role_status'] > 0 ){

  		$path_update = "update.php";

  		$version = 0.6;


  		$path_href = plugins_url("update.php", __FILE__);
  	


  		//if( file_exists($path_href) ){


  		//}  		

  		echo "<br>  <h3 class='part_header' style='color:grey;'> Управление таблицами данных </h3> <hr>";

	  	$view = new ViewORM('user');
	  	if($view->granted){
	  		createView($view);	
	  	}
	  	

	  	$view = new ViewORM('role');
	  	if($view->granted){
		  	createView($view);
		  }


	  	$view = new ViewORM('teacher');
	  	if($view->granted){
		  	createView($view);
		  }


	  	$view = new ViewORM('client');
	  	if($view->granted){
		  	createView($view);
		  }


	  	$view = new ViewORM('coursestatus');
	  	if($view->granted){
		  	createView($view);
		  }


	  	$view = new ViewORM('paystatus');
	  	if($view->granted){
		  	createView($view);
		  }


	  	$view = new ViewORM('course');
	  	if($view->granted){
		  	createView($view);
		  }

		$view = new ViewORM('form');
	  	if($view->granted){
		  	createView($view);
		  }
 

		$view = new ViewORM('teachercourse');
	  	if($view->granted){
		  	createView($view);
		  }  

        
			



	}


  	

	include_once "includes/footer.php";
							  
	//$array_for_required_table = array("wp_users","role","user","course","client","coursestatus","paystatus","teacher", "formoftraining");
	$array_for_required_table = array("wp_users","role","user","user_client","user_teacher","course","client","coursestatus","paystatus","teacher","form");
	getFooter($array_for_required_table);

}	


add_action("wp_ajax_plugin_tables", "plugin_tables");
add_action("wp_ajax_zakaz_zvonka", "zakaz_zvonka");
add_action("wp_ajax_profile_ajax", "profile_ajax");
add_action("wp_ajax_test_ajax", "test_ajax");
add_action("wp_ajax_noprivtest_ajax", "test1_ajax");
add_action("wp_ajax_mail_ajax", "mail_ajax");

add_action("admin_post_nopriv_submit-form", "test_register");


//add_action("wp_ajax_nopriv_zakaz_zvonka", "zakaz_zvonka");

function test_register(){
	echo "worked";
	include_once "includes/register.php";
	new_user();	
}


function test1_ajax(){
	
}

function mail_ajax(){
	global $wpdb;
	include_once "includes/functions.php";
  	include_once "includes/mails.php";
  	$user = UsersORM::getUser();

  	if(invalidUser()){
  		return false;
  	}

  	$data = $_POST['mail_data'];
  	
  	if($data["method"]=="getMailInbox"){
  		$mail_id = $data['mail_id'];
  		//secho $mail_id;
  		$res = getTimeMailInbox($user, $mail_id);
  		echo $res;
  	}else if($data["method"]=="sendMail"){
  		$data1["recepient_userid"] = $data["user_id"];
  		$data1["mail_title"] = $data["mail_title"];
  		$data1["mail_body"] = $data["mail_body"];
  		$res = sendTimeMail($data1);
  		echo $res;
  	}else if($data["method"]=="setReaded"){
  		$data1["mail_id"] =  $data["mail_id"];  
  		setReaded($data1);
  	}
	
}


function profile_ajax(){

	include 'includes/profile_teacher_functions.php';

	$method = $_POST['method'];
	$data = $_POST['data'];
	

	echo("add0");
	


	if( $method == "teacher_add_1" ){
		$res = teacher_add_1($data);
		echo json_encode($res);
	}elseif( $method == "teacher_add_2" ){
		$res = teacher_add_2($data);
		echo json_encode($res);
	}elseif( $method == "teacher_add_3" ){
		$res = teacher_add_2($data);
		echo json_encode($res);
	}elseif( $method == "teacher_add_4" ){
		$res = teacher_add_2($data);
		echo json_encode($res);
	}elseif( $method == "teacher_add_5" ){
		$res = teacher_add_2($data);
		echo json_encode($res);
	}elseif( $method == "teacher_add_final" ){

		echo("add1");

		$res = teacher_add_final($data);
		echo json_encode($res);
	}

}

function test_ajax(){
	global $wpdb;
	include 'includes/functions.php';
	include 'includes/register.php';
	include 'includes/addcourse.php';
	include 'includes/helpears.php';
	include 'includes/payform.php';
	
	$table_name = $_POST['table_name'];
	$table_method = $_POST['table_method'];
	$table_data = $_POST['table_data'];
	

	//$res = "method";
	
	if($table_method=="update"){
		$view = new ViewORM($table_name);
		$res = $view->update($table_data);
		echo json_encode($res);
	}elseif($table_method=="delete"){
		$view = new ViewORM($table_name);
		$res = $view->delete($table_data);
		echo json_encode($res);
	}elseif($table_method=="insert"){
		$view = new ViewORM($table_name);
		$res = $view->insert($table_data);
		echo json_encode($res);
	}elseif($table_method=="search"){
		$view = new ViewORM($table_name);
		$view = new ViewORM('clientcourse');
		if ($table_data['reset'] == 1) {
			$res = $view->findAll();
		}else{
			$searchkey = $table_data['searchkey'];
			$res = $view->findWhere($searchkey);
		} 
		echo json_encode($res);
	}elseif($table_method=="register"){
		new_user($table_data);
	}elseif($table_method=="addcourse"){
		echo "addcourse";
		addcourse($table_data);
	}elseif($table_method=="delcourse"){
		echo "delcourse";
		delcourse($table_data);
	}elseif($table_method=="searchUsers"){
		searchUsers($table_data);
		//echo json_encode($res);
	}elseif($table_method=="payment"){
		payment($table_data);	
	};
	

	
	//echo json_encode($res);
	//return json_encode($res);
}


function plugin_tables(){
	global $wpdb;
	include 'includes/functions.php';

	

	$method = $_SERVER['REQUEST_METHOD'];

	if($method == 'GET') {
		/*
		$table_name = "user";
		$table_data = array(
				"iduser"  => "1",
				"role_id" => "2",
				'wp_user_id' => "1"
			);
		$view = new ViewORM($table_name);
		echo $view->update($table_data);
		*/

		
		die();

	} elseif ($method == 'POST') {
		$table_name = $_POST['table_name'];
		$table_data = $_POST['table_data'];
		/*$view = new ViewORM($table_name);
		$view->update($table_data);*/
		return "OK";
		//die();
	}elseif ($method=='PUT') {
		//update record
	}

	echo "fsfsdf";
}
 
function zakaz_zvonka(){

  global $wpdb;
  include "includes/functions.php";

  $table_name = "";
  $data = "";
  
 	
  	$table = new TableORM('wp_users');
	echo json_encode($table);
	echo $table->name;
	echo "<br>";
	echo json_encode( $table->findAllForSelect() );
	$res = $table->findAllForSelect();
	echo "select $table_name";
	echo "<br>";
	echo json_encode($res);
  	die();
}

function myplugin_activate() {
	include 'includes/install_plug.php';
	install_db();
}


function my_uninstall(){
	/*include 'includes/uninstall_plug.php';
	uninstall_db();*/
}


//Генерация ответа
function sendResponseDengiOnline($status, $message = ''){
     $response = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
     $response .= '<result>'."\n";
       $response .= '<code>'.$status.'</code>'."\n";
    $response .= '<comment>'.$message.'</comment>'."\n";
    $response .= '</result>';
      die($response);
}

//Проверка существования идентификатора пользователя или заказа
function checkUser($userID){
	global $wpdb;
	$prefix = "timetable_";
     $sql = "SELECT idorder FROM  {$prefix}order_new WHERE order_number = '".$userID ."'";
     $res = $wpdb->get_row($sql, ARRAY_A);
     if($res == null){
          return FALSE;
     }
     return TRUE;
}

//Проверка, не приходило ли оповещение о таком идентификаторе платежа ранее
function checkDuplicateDengiOnline($ODPaymentID){
	global $wpdb;
	$prefix = "timetable_";
  
     $sql = "SELECT status FROM {$prefix}payment WHERE od_payment_id = ".intval($ODPaymentID);
    
	 $res = $wpdb->get_row($sql, ARRAY_A);


     if($res == null){
          return FALSE;
     }

     $status = $res['status'];
     //Платеж успешно выполнен ранее
     if($status == 'SUCCESS'){
          return TRUE;
     }
     else{
          return FALSE;
     }
}



function post1(){
	global $wpdb;
	$prefix = "timetable_";

	$post_var = array();

	if( isset($_GET['amount']) ){
		$post_var['amount'] = $_GET['amount'];
	}
	if( isset($_GET['userid']) ){
		$post_var['userid'] = $_GET['userid'];
	}
	if( isset($_GET['paymentid']) ){
		$post_var['paymentid'] = $_GET['paymentid'];
	}
	if( isset($_GET['key']) ){
		$post_var['key'] = $_GET['key'];
	}
	if( isset($_GET['keygen']) ){
		$post_var['keygen'] = $_GET['keygen'];
	}
	if( isset($_GET['paymode']) ){
		$post_var['paymode'] = $_GET['paymode'];
	}
	if( isset($_GET['userid_extra']) ){
		$post_var['userid_extra'] = $_GET['userid_extra'];
	}
	if( isset($_GET['orderid']) ){
		$post_var['orderid'] = $_GET['orderid'];
	}

	if( isset($_GET['test']) ){
		$post_var['test'] = $_GET['test'];
		$test = $post_var['test'];
	}else{
		$test = 0;
	}

	echo json_encode($post_var);
	if($test == 1) {
		include_once 'includes/payment_settings.php';
		include_once 'includes/payment_status.php';
		$project_settings = payment_settings();		
		echo "working with db";

		$secretKey = $project_settings['secret'];

		$projectHash = md5(	$post_var['amount'].$post_var['userid'].$post_var['paymentid'].$secretKey );
		if($projectHash != $post_var['key']){
		     sendResponseDengiOnline('NO', 'Контрольная подпись запроса неверна.');
		}
		if(floatval($post_var['amount']) == 0 && intval($post_var['paymentid']) == 0){
		     
			 //Это запрос на проверку идентификатора пользователя или заказа
		     if(checkUser($post_var['userid'])){
		          sendResponseDengiOnline('YES', 'Идентификатор существует');
		     }
		     else{
		          sendResponseDengiOnline('NO', 'Идентификатор не найден');
		     }
		}
		if(filter_var($post_var['amount'], FILTER_VALIDATE_FLOAT) &&
		filter_var($post_var['paymentid'], FILTER_VALIDATE_INT)
		          && floatval($post_var['amount']) > 0 && intval($post_var['paymentid']) > 0){

		     //Это запрос на проведение оплаты в проект
		     if(!checkDuplicateDengiOnline($post_var['paymentid'])){
		          //совершаем действия по начислению денежных средств пользователю

		     		$sql= "SELECT idorder, user_id, clientcourse_id FROM {$prefix}order_new WHERE order_number = '" . $post_var['userid'] . "'";
				 	$order = $wpdb->get_row($sql, ARRAY_A);
				 	if($order == null){
				 		sendResponseDengiOnline('NO', 'Идентификатор не найден');		
				 	}



				 	$wpdb->insert(
				 			$prefix."payment",
				 			array(
				 					"user_id"=> $order['user_id'],
				 					"clientcourse_id"=> $order['clientcourse_id'],
				 					"payment_amount"=> $post_var['amount'],
				 					"order_id"=> $order['idorder'],
				 					"status"=> "SUCCESS",
				 					"od_payment_id"=> $post_var['paymentid']
				 				),
				 			array(
									'%d',
									'%d',
									'%d',
									'%d',
									'%s',
									'%d',
				 				)
				 		);
 				    checkPaymentCourse( $order['clientcourse_id'] );
		            sendResponseDengiOnline('YES', 'Текущий статус платежа.');

		     }
		     else{
		          sendResponseDengiOnline('YES', 'Платеж был успешно выполнен ранее.');
		     }
		}

	}
	
	
}

function pgw(){

	$post_var = array();

	if( isset($_GET['amount']) ){
		$post_var['amount'] = $_GET['amount'];
	}
	if( isset($_GET['userid']) ){
		$post_var['userid'] = $_GET['userid'];
	}
	if( isset($_GET['paymentid']) ){
		$post_var['paymentid'] = $_GET['paymentid'];
	}
	if( isset($_GET['key']) ){
		$post_var['key'] = $_GET['key'];
	}
	if( isset($_GET['paymode']) ){
		$post_var['paymode'] = $_GET['paymode'];
	}
	if( isset($_GET['userid_extra']) ){
		$post_var['userid_extra'] = $_GET['userid_extra'];
	}
	if( isset($_GET['orderid']) ){
		$post_var['orderid'] = $_GET['orderid'];
	}
	echo json_encode($post_var);

}





register_activation_hook( __FILE__, 'myplugin_activate' );
register_uninstall_hook( __FILE__, 'my_uninstall' );
add_shortcode('timetable','my_plugin');
add_action('admin_post_wpse_79898','post1');
add_action('admin_post_nopriv_wpse_79898','post1');
add_action('admin_post_pgw','pgw');


?>